package com.gator.desig_mode.interpreter;

import java.util.Map;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc 抽象解释器
 */
public abstract class Expression {

  /**
   * @param var key 即表达式（如 a b c ...） value 即具体值，表达式对应的值 如 {a = 10 , b = 20}
   * @describe
   * @author 何章怀晓 hezhanghuaixiao
   * @date 2022/3/17  18:32
   * @other
   */
  public abstract int interpreter(Map<String, Integer> var);

}


//变量解释器,将变量对应的具体数字返回
class VarExpression extends Expression {

  private String key; // 即 key = a ; key = b ; key = ....

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public VarExpression(String key) {
    this.key = key;
  }

  /**
   * @param var 键值对, 通过key获取对应的值
   * @return int
   * @describe
   * @author 何章怀晓 hezhanghuaixiao
   * @date 2022/3/17  18:37
   * @other
   */
  @Override
  public int interpreter(Map<String, Integer> var) {

    return var.get(this.key);
  }
}


//抽象运算符号解析器 特点：每个运算符号只和左右两个值有关系
//左右也可能是解析后的结果（结果暂存），均为Expression子类
//该类是非终结符号，下有具体子类实现
class SymbolExpression extends Expression {

  private Expression left; //非终结符聚合Expression

  private Expression right;

  public SymbolExpression(Expression left, Expression right) {
    this.left = left;
    this.right = right;
  }

  public Expression getLeft() {
    return left;
  }

  public void setLeft(Expression left) {
    this.left = left;
  }

  public Expression getRight() {
    return right;
  }

  public void setRight(Expression right) {
    this.right = right;
  }

  //默认实现，下有具体实现如 + - ...
  @Override
  public int interpreter(Map<String, Integer> var) {
    return 0;
  }
}

//具体加法解释器
class AddExpression extends SymbolExpression {


  public AddExpression(Expression left, Expression right) {
    super(left, right);
  }


  //将左右表达式相加
  @Override
  public int interpreter(Map<String, Integer> var) {
    return
        super.getLeft() // left是 + 左边的表达式对应的value，如a  = 10; 返回 10  ...
            .interpreter(var)
            + super.getRight()
            .interpreter(var);
  }
}


//具体加法解释器
class SubExpression extends SymbolExpression {


  public SubExpression(Expression left, Expression right) {
    super(left, right);
  }


  //将左右表达式相减
  @Override
  public int interpreter(Map<String, Integer> var) {
    return
        super.getLeft() // left是 + 左边的表达式对应的value，如a  = 10; 返回 10  ...
            .interpreter(var)
            - super.getRight()
            .interpreter(var);
  }
}
